<template>
	<view>
		<!-- 标签页 -->
		<view class="tab">
			<view class="tabItem" v-for="(item,index) in tabs" :key="index" @click="clickTabItem(index)">
				<text :class="[{sortFilter : index == 0 || (curTab === index && isPop)}]">{{item}}</text>
				<view v-if="index === 0" style="display: inline;">
					<image v-if="curTab === 0 && isPop" src="/static/common/arrow_lightUp.png"></image>
					<image v-else src="/static/common/arrow_lightDown.png"></image>
				</view>

				<view v-else style="display: inline;">
					<image v-if="curTab === index && isPop" src="/static/common/arrow_lightUp.png"></image>
					<image v-else src="/static/common/arrow_defaultDown.png"></image>
				</view>
			</view>
		</view>

		<!-- 弹出框 -->
		<view class="popCss" :style="{'top':curTop+'px'}" @touchmove.stop.prevent="" v-if="isPop">
			<!-- 推荐排序 -->
			<view class="sortType show" :class="{show : curTab == 0}" v-if="curTab==0" @touchend.stop>
				<view class="sortItem" v-for="(item,index) in sortData" :key="item.code" @click.stop="chooseSort(item)">
					<text class="title" :class="{active : sortCode === item.code}">{{item.text}}</text>
					<u-icon v-if="sortCode === item.code" name="checkbox-mark" color="#1573FF"></u-icon>
				</view>
			</view>
			<!-- 车型/配置 -->
			<view class="filterBox show" v-if="curTab==1" @touchend.stop>
				<scroll-view scroll-y="true" class="scroll-view">
					<view v-for="(item,index) in carConfig" :key="index">
						<view class="section-title">{{item.title}}</view>
						<view class="label-box">
							<filterCheckbox ref="checkbox" @change="onChange" :keyName="item.key"></filterCheckbox>
						</view>
					</view>
				</scroll-view>
				<view class="btn-box">
					<view class="totalBox">
						<view class="totalInfo">
							车型:<text style="color: #1989FA;">{{count}}</text>款
						</view>
					</view>

					<view>
						<view class="btn btn1" @click.stop="filterClear(1)">清除</view>
						<view class="btn btn2" @click.stop="filterResult">完成</view>
					</view>

				</view>
			</view>
			<!-- 品牌 -->
			<view class="filterBox show" v-if="curTab==2">
				<scroll-view scroll-y="true" class="scroll-view">
					<view v-for="(item,index) in carBrand" :key="index">
						<view class="section-title">{{item.title}}</view>
						<view class="label-box">
							<filterCheckbox ref="checkbox" @change="onChange" :keyName="item.key"></filterCheckbox>
						</view>
					</view>
				</scroll-view>
				<view class="btn-box">
					<view class="totalBox">
						<view class="totalInfo">
							车型:<text style="color: #1989FA;">{{count}}</text>款
						</view>
					</view>

					<view>
						<view class="btn btn1" @click.stop="filterClear(2)">清除</view>
						<view class="btn btn2" @click.stop="filterResult">完成</view>
					</view>
				</view>
			</view>
			<!-- 优惠/价格 -->
			<view class="filterBox show" v-if="curTab==3">
				<scroll-view scroll-y="true" class="scroll-view">
					<view v-for="(item,index) in priceDiscount" :key="index">
						<view class="section-title">{{item.title}}</view>
						<view class="label-box">
							<filterCheckbox ref="checkbox" @change="onChange" :keyName="item.key"></filterCheckbox>
						</view>
					</view>
				</scroll-view>
				<view class="btn-box">
					<view class="totalBox">
						<view class="totalInfo">
							车型:<text style="color: #1989FA;">{{count}}</text>款
						</view>
					</view>

					<view>
						<view class="btn btn1" @click.stop="filterClear(3)">清除</view>
						<view class="btn btn2" @click.stop="filterResult">完成</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import filterCheckbox from '@/components/filter-checkbox/filter-checkbox.vue';
	var filterData = require('@/static/content.json');
	import merge from 'lodash/merge';
	import concat from 'lodash/concat';
	import {
		initData,
		classificationMoldelCount
	} from 'api/home-api.js'

	export default {
		components: {
			filterCheckbox
		},
		data() {
			return {
				curTab: null,
				curTop: 82, //弹框距离顶部的距离
				isPop: false, //是否显示筛选弹框
				count: 0,
				// 筛选标题
				// tabs: ['推荐排序', '车型配置', '品牌筛选', '价格/优惠'],
				//筛选数据源
				sortData: this.$store.state.initData.initData.sortData, //排序
				carConfig: this.$store.state.initData.initData.carConfig, //车型配置,
				carBrand: this.$store.state.initData.initData.brand, //品牌,
				priceDiscount: this.$store.state.initData.initData.activity, //价格优惠
				//排序code
				sortCode: 0,
				/** 参数容器 */
				params: {
					seat: [], //座位
					speedChangingBox: [], //档位
					modelConfig: [], //车型配置
					brand: [], //品牌
					priceSection: '', //价格区间
					activity: '', //优惠活动
				},
				/** 缓存容器 */
				buffer: {
					seat: [], //座位
					speedChangingBox: [], //档位
					modelConfig: [], //车辆配置
					brand: [], //品牌
					priceSection: '', //日均价
					activity: '', //优惠活动
				},
			}
		},

		props: {
			classification: {
				type: String | Number,
				default: 0
			},
			storeId: {
				type: String,
				default: '',
			}
		},

		computed: {
			/** 车座 */
			seatData() {
				return this.carConfig.filter(val => val.key == 'seat')[0];
			},
			/** 档位 */
			speedChangingBoxData() {
				return this.carConfig.filter(val => val.key == 'speedChangingBox')[0];
			},
			/** 车辆配置 */
			modelConfigData() {
				return this.carConfig.filter(val => val.key == 'modelConfig')[0];
			},
			/** 品牌 */
			brandData() {
				return this.carBrand.filter(val => val.key == 'brand')[0];
			},
			/** 价格 */
			priceData() {
				return this.priceDiscount.filter(val => val.key == 'priceSection')[0];
			},
			/** 优惠 */
			youhuiData() {
				return this.priceDiscount.filter(val => val.key == 'activity')[0];
			},
			/** 车型配置选项卡名称 */
			carConfigTitle() {
				let title = '';
				// 拿取车座名称
				const seatTitle = this.seatData?.data?.list
					?.filter(val => this.params.seat.includes(val.code))
					?.map(val => val.text) ?? [];
				// 拿取档位名称
				const speedChangingBoxTitle = this.speedChangingBoxData?.data?.list
					?.filter(val => this.params.speedChangingBox.includes(val.code))
					?.map(val => val.text) ?? [];
				// 车辆配置
				const modelConfigTitle = this.modelConfigData?.data?.list
					?.filter(val => this.params.modelConfig.includes(val.code))
					?.map(val => val.text) ?? [];
				title += concat(seatTitle, speedChangingBoxTitle, modelConfigTitle).toString();
				if (title.length > 6) {
					title = title.substr(0, 6) + "...";
				}
				return title || '车型配置';
			},
			/** 品牌选项卡名称 */
			brandTitle() {
				let title = '';
				// 拿取品牌名称
				const brandTitle = this.brandData?.data?.list
					?.filter(val => this.params.brand.includes(val.code))
					?.map(val => val.text) ?? [];
				title += concat(brandTitle).toString();
				if (title.length > 6) {
					title = title.substr(0, 6) + "...";
				}
				return title || '品牌筛选';
			},
			/** 价格优惠选项卡名称 */
			priceTitle() {
				let title = '';
				// 拿取价格名称
				const priceTitle = this.priceData?.data?.list
					?.filter(val => this.params.priceSection.includes(val.code))
					?.map(val => val.text) ?? [];
				// 拿取优惠名称
				const youhuiTitle = this.youhuiData?.data?.list
					?.filter(val => this.params.activity.includes(val.code))
					?.map(val => val.text) ?? [];
				title += concat(priceTitle, youhuiTitle).toString();
				if (title.length > 6) {
					title = title.substr(0, 6) + "...";
				}
				return title || '价格/优惠';
			},
			// 筛选标题
			tabs() {
				return ['推荐排序', this.carConfigTitle, this.brandTitle, this.priceTitle];
			},
		},
		async created() {
			//获取初始化数
			await initData(this.$store.state.user.tenantId).then(res => {
				// console.log(res);
				let initData = res.data;
				this.$store.commit('initData/saveInitData', initData);
			})
			console.log('this.carConfig', this.carConfig);
			console.log('this.priceDiscount', this.priceDiscount);
			setTimeout(()=>{
				this.getCount();
			},1000)
			
		},
		methods: {
			/** 重设缓存容器 */
			resetBuffer() {
				this.buffer = JSON.parse(JSON.stringify(this.params));
				delete this.priceData?.data?.index;
				delete this.youhuiData?.data?.index;
				// this.priceData?.data?.list?.forEach(val => delete val.index);
				// this.youhuiData?.data?.list?.forEach(val => delete val.index);
				console.log('this.buffer', this.buffer);
				this.reRender();
			},
			/** 清空缓存容器 */
			clearBuffer() {
				this.buffer = {
					seat: [], //座位
					speedChangingBox: [], //档位
					modelConfig: [], //车辆配置
					brand: [], //品牌
					priceSection: '', //日均价
					activity: '', //优惠活动
				};
				this.reRender();
			},
			/**
			 * 设置filterCheckBox选中状态
			 * @param {Object} item 选中数据
			 * @param {Object[]} item.list 选中数据
			 * @param {Boolean} item.list.checked 选中数据
			 * @param {String} item.list.code 选中码
			 * @param {String} item.list.text 选中文字
			 * @param {String[]} checked 历史选中数组
			 * @param {String} type 选择类型
			 */
			setFilterCheckBox(item, checked, type) {
				// console.log('setFilterCheckBox:item', item);
				// console.log('setFilterCheckBox:checked', checked);
				// console.log('setFilterCheckBox:type', type);
				item.list.forEach((val, index) => {
					if (type == 'checkbox') {
						/** 多选 */
						/** 设置选中状态: checked中的数据为选中数据的code。这里还原选中状态判断历史选中数据有无code即可。 */
						this.$set(val, 'checked', checked?.includes(val.code) ?? false);
					} else if (type == 'radio') {
						/** 单选 */
						// console.log('val.code, checked', val.code, checked);
						if (val.code == checked) {
							this.$set(item, 'index', index);
						}
					}
				});
			},
			/** 
			 * 渲染标签页内容
			 */
			renderTabPage(items) {
				items.forEach((item, index) => {
					// 给每一个 组件调用一次 set 方法
					setTimeout(() => {
						const data = item.data;
						// console.log('item', item);
						this.setFilterCheckBox(data, this.params[item.key], data.type);
						setTimeout(() => {
							// console.log(JSON.stringify(data))
							this.$refs.checkbox[index]?.set(data);
						}, 100);
					}, 100)
				})
			},
			reRender() {
				if (this.curTab == 1) {
					this.renderTabPage(this.carConfig);
				}
				if (this.curTab == 2) {
					this.renderTabPage(this.carBrand);
				}
				if (this.curTab == 3) {
					this.renderTabPage(this.priceDiscount);
				}
			},
			/** 点击标签页 */
			clickTabItem(index) {
				this.resetBuffer();
				if (this.curTab == index) {
					this.isPop = !this.isPop;
				} else {
					this.isPop = true;
				}
				this.curTab = index;

				if (this.curTab != 0) {
					this.$nextTick(() => {
						if (this.curTab == 1) {
							this.renderTabPage(this.carConfig);
						}
						if (this.curTab == 2) {
							this.renderTabPage(this.carBrand);
						}
						if (this.curTab == 3) {
							this.renderTabPage(this.priceDiscount);
						}
					})
				}
			},
			// 排序选择
			chooseSort(item) {
				this.sortCode = item.code;
				this.tabs[0] = item.text;
				this.isPop = !this.isPop;
				this.$emit('changeSort', this.sortCode);
			},
			/**
			 * 标签发生改变
			 * @param {Object[]} data 选中数据
			 * @param {Boolean} data.checked 选中数据
			 * @param {String} data.code 选中码
			 * @param {String} data.text 选中文字
			 * @param {String} keyName 操作组的键
			 */
			onChange(data, keyName) {
				// 这里的逻辑为：选中放入暂存容器，点击完成按钮将缓存放入实际参数中。
				// console.log('data', data);
				// console.log('keyName', keyName);
				if (keyName == 'seat') { //座位
					this.buffer.seat = [];
					data?.forEach(item => {
						this.buffer.seat.push(item.code);
					})
				}
				if (keyName == 'speedChangingBox') { //档位
					this.buffer.speedChangingBox = [];
					data?.forEach(item => {
						this.buffer.speedChangingBox.push(item.code);
					})
				}
				if (keyName == 'modelConfig') { //车型配置
					this.buffer.modelConfig = [];
					data?.forEach(item => {
						this.buffer.modelConfig.push(item.code);
					})
				}
				if (keyName == 'brand') { //品牌
					this.buffer.brand = [];
					data?.forEach(item => {
						this.buffer.brand.push(item.code);
					})
				}
				if (keyName == 'priceSection') { //日均价
					this.buffer.priceSection = data.code;
				}
				if (keyName == 'activity') { //优惠活动
					this.buffer.activity = data.code;
				}


               this.getCount();
				
			},

			//筛选清除
			filterClear(type) {
				if (type == 1) {
					this.$set(this.params, 'seat', []);
					this.$set(this.params, 'speedChangingBox', []);
					this.$set(this.params, 'modelConfig', []);
				}
				if (type == 2) {
					this.$set(this.params, 'brand', []);
				}
				if (type == 3) {
					this.$set(this.params, 'priceSection', '');
					this.$set(this.params, 'activity', '');
				}
				this.resetBuffer();
				
				 this.getCount();
			},
			//筛选完成
			filterResult() {
				/** 把缓存数据拷贝给参数数据 */
				this.params = JSON.parse(JSON.stringify(this.buffer));
				/** 点击完成时，将buff的数据写入 */
				var filterDic = {
					'seat': this.params.seat.length > 0 ? this.params.seat : null,
					'speedChangingBox': this.params.speedChangingBox.length > 0 ? this.params.speedChangingBox : null,
					'modelConfig': this.params.modelConfig.length > 0 ? this.params.modelConfig : null,
					'brandId': this.params.brand.length > 0 ? this.params.brand : null,
					'priceType': this.params.priceSection,
					'activity': this.params.activity
				}
				console.log(filterDic);
				this.isPop = false;
				this.$emit('filterFinish', filterDic);

			},

			// 获取统计数
			getCount() {
				classificationMoldelCount({
					tenantId: this.$store.state.user.tenantId,
					storeId: this.$store.state.user.takeStoreId,
					startTime: this.$store.state.order.startTime,
					endTime: this.$store.state.order.endTime,
					classification: this.classification,
					seat: this.buffer.seat.length > 0 ? this.buffer.seat : null,
					speedChangingBox: this.buffer.speedChangingBox.length > 0 ? this.buffer.speedChangingBox :
						null,
					modelConfig: this.buffer.modelConfig.length > 0 ? this.buffer.modelConfig : null,
					brandId: this.buffer.brand.length > 0 ? this.buffer.brand : null,
					priceType: this.buffer.priceSection,
					activity: this.buffer.activity,
					bizType : 1,

				}).then(res => {
					this.count = res.data;
				})
			},
		}

	}
</script>

<style lang="scss" scoped>
	.tab {
		margin-top: 20rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		color: #333;
		font-size: 26rpx;

		.tabItem {
			display: inline;

			.sortFilter {
				color: #1573ff;
			}

			image {
				width: 20rpx;
				height: 20rpx;
			}
		}
	}

	.popCss {
		position: fixed;
		right: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		background: rgba(0, 0, 0, 0.4);
		bottom: var(--window-bottom);
		z-index: 111;

		.sortType {
			max-height: 608rpx;
			background: #fff;
			overflow: hidden;
			padding: 20rpx 20rpx 0;
			border-radius: 0 0 20rpx 20rpx;

			.sortItem {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 1px solid #efefef;
				height: 80rpx;

				.title {
					color: #333;
					font-size: 26rpx;

					&.active {
						color: #1573ff;
						font-weight: bold;
					}
				}
			}
		}

		.filterBox {
			background-color: #fff;
			height: 500rpx;
			padding: 20rpx 20rpx 120rpx;
			border-radius: 0 0 20rpx 20rpx;

			.scroll-view {
				height: 500rpx;
				overflow-y: scroll;
			}

			.section-title {
				color: #333;
				font-size: 28rpx;
				font-weight: bold;
				margin-left: 20rpx;

				&::before {
					content: "";
					display: inline-block;
					width: 8rpx;
					height: 30rpx;
					background: #009cf9;
					position: relative;
					top: 6rpx;
					margin-right: 10rpx;
				}
			}

			.label-box {
				// width: 100%;
				margin-top: 20rpx;
			}
		}
	}

	.btn-box {
		height: 110rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.totalBox {
			.totalInfo {
				color: #131313;
				font-size: 26rpx;
			}
		}

		.btn {
			display: inline-block;
			margin-left: 18rpx;
			width: 215rpx;
			height: 90rpx;
			line-height: 90rpx;
			text-align: center;
			font-size: 30rpx;
			font-weight: bold;
			border-radius: 10rpx;
		}

		.btn1 {
			border: #009cf9 1px solid;
			color: #009cf9;
			background: #fff;
		}

		.btn2 {
			color: #fff;
			background: linear-gradient(90deg, #32ace9 0%, #176cfb 100%);
		}
	}

	.show {
		transition: all 0.6s ease;
		// transform: translateY(0%) !important;
	}

	// 隐藏滚动条
	scroll-view ::-webkit-scrollbar {
		width: 0;
		height: 0;
		background-color: transparent;
	}
</style>
